﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Caching;

namespace Thallo {
    class DependencyExpiration : ICacheItemExpiration,IDisposable {

        private MethodDescriptor MethodInfo { get; set; }
        EventHandler<EventArgs> _invokehandler;
        EventHandler<EntityUpdateEventArgs> _updatehandler;
        bool _expired = false;
        Type _dependencyType;
        public DependencyExpiration(MethodDescriptor mi) {
            MethodInfo = mi;
            _invokehandler = new EventHandler<EventArgs>(InvocationContext_MethodInvoked);
            InvocationContext.Invoked += _invokehandler;
            if( mi.UpdateMode == UpdateMode.Auto)
                _dependencyType = mi.Method.ReturnType;
            _updatehandler = new EventHandler<EntityUpdateEventArgs>(InvocationContext_Updated);
            if (_dependencyType != null)
                InvocationContext.DataChanged += _updatehandler;
        }

        void InvocationContext_Updated(object sender, EntityUpdateEventArgs e) {
            if (e.EntityType == _dependencyType)
                _expired = true;
        }

        void InvocationContext_MethodInvoked(object sender, EventArgs e) {
            var context = sender as InvocationContext;
            if (context == null)
                return;
            if (MethodInfo.DependencyAttributes != null)
                _expired = MethodInfo.DependencyAttributes.Any(c=> context.MethodBase.DeclaringType == c.Type
                        && context.MethodInfo.Name == c.MethodName);
        }

        public bool HasExpired() {
            return _expired;
        }

        public void Initialize(CacheItem owningCacheItem) {
            
        }

        public void Notify() {
            
        }

        public void Dispose() {
            InvocationContext.Invoked -= _invokehandler;
            InvocationContext.DataChanged -= _updatehandler;
        }

        
    }
}
